package com.imay.live.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.imay.capturefilter.filter.imay.IF1977Filter;
import com.imay.live.R;
import com.imay.live.adapter.CallLiveAdapter;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.manager.AccountManager;
import com.imay.live.model.CallLiveListModel;
import com.imay.live.model.CallLiveModel;
import com.imay.live.model.CallLiveResultModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.RecyclerViewUtil;
import com.imay.live.utils.TimeUtil;
import com.imay.live.view.refresh.RefreshView;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;

import java.util.ArrayList;
import java.util.List;

import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * Created by lzx on 2017/08/15 0015.
 * 召唤直播列表
 */

public class HoldCallLiveActivity extends BaseRequestActivity implements View.OnClickListener {
    static final String UID = "targetUid";
    static final String NICKNAME = "nickname";

    private TextView tv_call_count_live;
    private TwinklingRefreshLayout trl_refresh_call_live;
    private RecyclerView rcv_call_live;
    private Button btn_call_live;
    private TextView tv_call_live;
    private String loadCallLiveListCommand;
    private long userId;
    private int maxId;
    private CallLiveAdapter callLiveAdapter;
    private List<CallLiveListModel> callLiveListModels;
    private String nickname;
    private String callLiveCommand;
    private CallLiveTimer callLiveTimer;


    public static void startActivity(Context context, long uid,String nickname) {
        Intent starter = new Intent(context, HoldCallLiveActivity.class);
        starter.putExtra(UID, uid);
        starter.putExtra(NICKNAME, nickname);
        context.startActivity(starter);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.holdcall_content;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        userId = getIntent().getLongExtra(UID,0);
        nickname = getIntent().getStringExtra(NICKNAME);
        callLiveListModels = new ArrayList<>();
        setTitle(R.string.call_live);
        bindViews();
        loadCallLiveList();
    }

    private void bindViews() {

        tv_call_count_live = (TextView) findViewById(R.id.tv_call_count_live);
        trl_refresh_call_live = (TwinklingRefreshLayout) findViewById(R.id.trl_refresh_call_live);
        rcv_call_live = (RecyclerView) findViewById(R.id.rcv_call_live);
        btn_call_live = (Button) findViewById(R.id.btn_call_live);
        tv_call_live = (TextView) findViewById(R.id.tv_call_live);

        btn_call_live.setOnClickListener(this);

        RecyclerViewUtil.setLinearLayoutManagerWithoutDivider(this, rcv_call_live);

        RefreshView headerView = new RefreshView(this);
        trl_refresh_call_live.setHeaderView(headerView);
        trl_refresh_call_live.setBottomView(new LoadingView(this));
        trl_refresh_call_live.setEnableLoadmore(true);
        trl_refresh_call_live.setEnableOverScroll(false);
        trl_refresh_call_live.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                maxId = 0;
                loadCallLiveList();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                loadCallLiveList();
            }
        });
    }


    private void loadCallLiveList() {
        loadCallLiveListCommand = ProtoRequestHelper.task(ProtoHttpFactory.getCallLiveList(userId,20,maxId)).setTag(this.hashCode()).request(this);
    }
    private void callLive() {
        int random=(int)(Math.random()*4);
        callLiveCommand = ProtoRequestHelper.task(ProtoHttpFactory.getMakeLive(userId, getResources().getStringArray(R.array.CallLiveMessages)[random])).setTag(this.hashCode()).request(this);
    }

    @Override
    public void onRequestSuccess(String command, String data) {
        super.onRequestSuccess(command, data);
        refreshFinish();
        if (command.equals(loadCallLiveListCommand)){
            Result<CallLiveModel> result = JSON.parseObject(data,new TypeReference<Result<CallLiveModel>>(){}.getType());
            if (result.result==CodeSuccess){
                if (result.data==null){
                    return;
                }
                if (maxId==0){
                    callLiveListModels.clear();
                    refreshView(result.data);
                }
                List<CallLiveListModel> listModels =  result.data.getCallLiveList();
                if (listModels!=null&&!listModels.isEmpty()){
                    maxId = listModels.get(listModels.size()-1).getId();
                    callLiveListModels.addAll(result.data.getCallLiveList());
                    refreshView(result.data);
                }
                bindAdapter();

            }
        }else if(command.equals(callLiveCommand)){
            Result<CallLiveResultModel> result = JSON.parseObject(data,new TypeReference<Result<CallLiveResultModel>>(){}.getType());
            if (result.result==CodeSuccess){
                maxId = 0;
                loadCallLiveList();
            }
        }
    }

    @Override
    public void onRequestError(String command, int code, String message) {
        super.onRequestError(command, code, message);
        ErrorResult.toastError(this, code);
        refreshFinish();
    }

    private void bindAdapter(){
        if (callLiveAdapter == null){
            callLiveAdapter = new CallLiveAdapter(callLiveListModels);
            rcv_call_live.setAdapter(callLiveAdapter);
            callLiveAdapter.setEmptyView(LayoutInflater.from(this).inflate(R.layout.view_load_layout,null));
        }else{
            callLiveAdapter.setNewData(callLiveListModels);
        }

    }

    /**
     * 完成刷新
     */
    public void refreshFinish() {
        if (trl_refresh_call_live != null) {
            if (maxId == 0) {
                trl_refresh_call_live.finishRefreshing();
            } else {
                trl_refresh_call_live.finishLoadmore();
            }
        }
    }

    private boolean isSelf(){
        return userId == AccountManager.getInstance().getUid();
    }

    private void refreshView(CallLiveModel liveModel){
        if (liveModel==null)return;
        if (isSelf()){
            if (liveModel.getCallLiveCount()>0){
                tv_call_count_live.setText(String.format(getString(R.string.open_live_hint_liver),liveModel.getCallLiveCount()));
            }else{
                tv_call_count_live.setText("");
            }
            tv_call_live.setText(R.string.open_live);
            btn_call_live.setText(R.string.live_now);
            btn_call_live.setEnabled(true);

        }else{
            if (liveModel.getCallLiveCount()>0) {
                tv_call_count_live.setText(String.format(getString(R.string.open_live_hint_user), nickname, liveModel.getCallLiveCount()));
            }else{
                tv_call_count_live.setText("");
            }
            btn_call_live.setEnabled(liveModel.getFreezeTime()==0);
            tv_call_live.setText(R.string.call_live_open_setting);
            if (liveModel.getFreezeTime()>0){
                if (callLiveTimer == null){
                    callLiveTimer = new CallLiveTimer(liveModel.getFreezeTime()*1000,1000);
                    callLiveTimer.start();
                }
//                btn_call_live.setText(TimeUtil.getCallLiveTime(liveModel.getFreezeTime()));
            }else{
                btn_call_live.setText(R.string.call_live_now);
                if (callLiveTimer!=null){
                    callLiveTimer.cancel();
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_call_live:
                if (isSelf()){
                    RoomPushNormalActivity.startActivity(this);
                    MobclickAgent.onEvent(this,"kaibo_click");
                }else{
                    callLive();
                }
                break;
        }
    }
    class CallLiveTimer extends CountDownTimer {

        public CallLiveTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (millisUntilFinished==0){
                onFinish();
            }else{
                btn_call_live.setText(TimeUtil.getCallLiveTime(millisUntilFinished/1000));
            }
        }

        @Override
        public void onFinish() {
            btn_call_live.setEnabled(true);
            btn_call_live.setText(R.string.call_live_now);

        }
    }

}
